import Taro, { getCurrentPages } from '@tarojs/taro'
import {
  call, put, all, takeLatest, select
} from 'redux-saga/effects'
import {
  GET_SESSTIONS,
  UPDATE_ACTIVE_PATIENT_SESSION,
  GET_SESSTION_BY_ID,
  GET_PATIENT_SYSTEM_MESSAGE,
  GET_NEW_BELL_ALERT_NUMBER,
  GET_BELL_ALERTS,
  SET_TAB_BAR_BADGE,
  GET_UN_VIEWED_CONSULTATION,
} from '@ACTIONS/message'
import { DEFAULT_TAKE, PATIENT_TYPE } from '@CONSTANTS/common'
import { getPlatform } from '@UTILS/common'
import api from '@API'
import {
  getSessionsList,
  getBellAlertList,
  getMessage,
  getCurrentSessionId,
  getIsVisitor,
  getMyDoctorMessageCount,
  getCurrentSession
} from './dataSelect'

const getSessions = function* getSessions(action) {
  try {
    const { payload = {} } = action
    const { skip } = payload
    const list = yield select(getSessionsList)
    const realSkip = skip === 0 ? 0 : list.length
    const data = yield call(api.getSessions2, {
      ...payload,
      take: DEFAULT_TAKE,
      skip: realSkip,
    })
    const sessions = data.Sessions || []
    yield put({
      type: GET_SESSTIONS.SUCCESS,
      list: sessions,
      skip,
      canLoadSessions: sessions.length >= DEFAULT_TAKE
    })
  } catch (error) {
    yield put({ type: GET_SESSTIONS.FAILURE, error })
  }
}
const getSessionById = function* getSessionById(action) {
  try {
    const { sId } = action
    const currentSession = yield select(getCurrentSession)
    const result = yield call(api.getSessions2, { sId })
    const { Participants } = currentSession || {}
    const prePId = Participants?.[0]?.pid
    const preDId = Participants?.[1]?.uid
    const nextPId = result?.patient?.[0]?.pid
    const nextDId = result?.doctor?.[1]?.uid
    const msgCount = prePId && prePId === nextPId && preDId === nextDId ? { NewMessageCounts: 0 } : {}
    if (result.Sessions) {
      yield put({
        type: UPDATE_ACTIVE_PATIENT_SESSION.REQUEST,
        updateSession: { ...result.Sessions[0], ...msgCount }
      })
    }
  } catch (error) {
    yield put({ type: UPDATE_ACTIVE_PATIENT_SESSION.FAILURE, error })
  }
}

const getSystemMessage = function* getSystemMessage() {
  try {
    const result = yield call(api.getBellAlerts, { skip: 0, take: 1, skipMarkRead: true, unreadFirst: true })
    if (Array.isArray(result.Alerts)) {
      yield put({
        type: GET_PATIENT_SYSTEM_MESSAGE.SUCCESS,
        latestSystemMessage: result?.Alerts?.[0]
      })
    }
  } catch (error) {
    yield put({ type: GET_PATIENT_SYSTEM_MESSAGE.FAILURE, error })
  }
}
const getNewBellAlertsNumber = function* getNewBellAlertsNumber() {
  try {
    const currentSessionId = yield select(getCurrentSessionId)
    if (currentSessionId) return
    const result = yield call(api.getAllNewNotification)
    yield put({
      type: GET_NEW_BELL_ALERT_NUMBER.SUCCESS,
      data: result
    })
    yield put({
      type: SET_TAB_BAR_BADGE.REQUEST
    })
  } catch (error) {
    yield put({ type: GET_NEW_BELL_ALERT_NUMBER.FAILURE, error })
  }
}
const getUnViewedConsultationReport = function* getUnViewedConsultationReport() {
  try {
    const result = yield call(api.countUnViewedConsultationReport)
    yield put({
      type: GET_UN_VIEWED_CONSULTATION.SUCCESS,
      count: result
    })
    yield put({
      type: SET_TAB_BAR_BADGE.REQUEST
    })
  } catch (error) {
    yield put({ type: GET_UN_VIEWED_CONSULTATION.FAILURE, error })
  }
}

const getBellAlerts = function* getBellAlerts(action) {
  try {
    const { payload = {} } = action
    const { skip } = payload
    const list = yield select(getBellAlertList)
    const realSkip = skip === 0 ? 0 : list.length
    const data = yield call(api.getBellAlerts, { skip: realSkip, take: DEFAULT_TAKE })
    const { Alerts } = data
    yield put({
      type: GET_BELL_ALERTS.SUCCESS,
      bellAlertList: Alerts || [],
      skip,
      canLoadBellAlert: Alerts.length >= DEFAULT_TAKE
    })
  } catch (error) {
    yield put({ type: GET_BELL_ALERTS.FAILURE, error })
  }
}
const setTabBarBadge = function* setTabBarBadge() {
  try {
    const message = yield select(getMessage)
    const isVisitor = yield select(getIsVisitor)
    const myDoctorMessageCount = yield select(getMyDoctorMessageCount)
    const number = isVisitor ? 0 : message.newAlertNum + message.newChatMessageCount + message.unViewedConsulReportCount + myDoctorMessageCount
    if (getPlatform().isWX && getCurrentPages().length > 1) return
    if (!global.IS_TAKEDA_H5 && number > 0) {
      Taro.showTabBarRedDot({
        index: global.IS_TAKEDA_H5 ? 2 : 3,
      })
    } else {
      Taro.hideTabBarRedDot({ index: global.IS_TAKEDA_H5 ? 2 : 3 })
    }
  } catch (error) {
    yield put({ type: SET_TAB_BAR_BADGE.FAILURE, error })
  }
}
export default function* rootSaga() {
  yield all([
    takeLatest(GET_SESSTIONS.REQUEST, getSessions),
    takeLatest(GET_SESSTION_BY_ID.REQUEST, getSessionById),
    takeLatest(GET_PATIENT_SYSTEM_MESSAGE.REQUEST, getSystemMessage),
    takeLatest(GET_NEW_BELL_ALERT_NUMBER.REQUEST, getNewBellAlertsNumber),
    takeLatest(GET_BELL_ALERTS.REQUEST, getBellAlerts),
    takeLatest(SET_TAB_BAR_BADGE.REQUEST, setTabBarBadge),
    takeLatest(GET_UN_VIEWED_CONSULTATION.REQUEST, getUnViewedConsultationReport)
  ])
}
